import React, {useState} from 'react';
import {Badge, Grid, Paper, Tab, Tabs, Tooltip, Typography} from "@material-ui/core";
import {useDispatch, useSelector} from "react-redux";
import Button from "@material-ui/core/Button";
import {makeStyles} from "@material-ui/styles";
import {useHistory} from "react-router-dom";
import {createNewIndicatorRequest} from "../../../../../redux/reducers/gqiEditor";
import ListOfIndicators from "./ListOfIndicators/ListOfIndicators";
import ModalCreateNewIndicator from "./ModalCreateNewIndicator/ModalCreateNewIndicator";
import ListOfSelectedIndicators from "./ListOfIndicators/ListOfSelectedIndicators";
import ModalMessage from "../../Common/Modal/ModalMessage";
import EditIcon from '@material-ui/icons/Edit';
import DeleteIcon from '@material-ui/icons/Delete';
import {getAllPlatforms, resetIndicatorSession} from "../../../../../redux/reducers/editor";
import {resetAllErrors} from "../../../../../redux/reducers/errorMessages";
import AddIcon from "@material-ui/icons/Add";

const useStyles = makeStyles(theme => ({
  gutter: {
    margin: theme.spacing(2, 0, 2, 0)
  },
  buttonSpacing: {
    marginRight: theme.spacing(1)
  },
  gutterBottom: {
    margin: theme.spacing(0, 0, 2, 0)
  }
}));

export default function Indicator(props) {
  // Props
  const {classes, handleStepForward, handleStepBackward} = props;

  // Constants from Redux store
  const indicatorsSelected = useSelector((state) => state.gqiEditor.selectedData.indicators);
  const indicatorsData = useSelector((state) => state.gqiEditor.fetchedData.indicators);
  const selectedIndicators = useSelector(state => state.gqiEditor.selectedData.indicators);
  const selectedPlatforms = useSelector(state => state.editor.selectedData.platforms);
  const selectedIndicatorType = useSelector(state => state.gqiEditor.common.indicatorType);

  // Local constants
  const history = useHistory();
  const dispatch = useDispatch();
  const styles = useStyles();
  const [searchIndicator, setSearchIndicator] = useState("");
  const [indicatorType, setIndicatorType] = useState("All");
  const [openCreateNewIndicator, setOpenCreateNewIndicator] = useState(false);
  const [indicatorInProgress, setIndicatorInProgress] = useState(false);
  const [tabValue, setTabValue] = useState(0);


  const handleCreateIndicator = () => {
    setIndicatorInProgress(false);
    setOpenCreateNewIndicator(!openCreateNewIndicator);
  }

  const handleBackToIndicatorEditor = () => {
    dispatch(createNewIndicatorRequest(selectedIndicatorType));
    if (selectedIndicatorType === "Basic Indicator")
      history.push("/basic");
    // Else if statements can be added according to the type of indicator selected (future updates)
  }

  const handleChangeTabs = (event, tabValue) => {
    setTabValue(tabValue);
  }

  const handleResetIndicatorSession = () => {
    dispatch(resetIndicatorSession());
    dispatch(getAllPlatforms());
    dispatch(resetAllErrors());
  }


  return (
    <>
      <Grid container direction="column" lg={9} className={styles.gutterBottom}>
        <Paper square>
          <Tabs
            value={tabValue} indicatorColor="primary" textColor="primary"
            variant="fullWidth" onChange={handleChangeTabs}
          >
            <Tab label="Available Indicators"/>
            <Tab label={
              <Badge badgeContent={selectedIndicators.length} color="primary"> List of Selected Indicators </Badge>}/>
          </Tabs>
        </Paper>

        {tabValue === 0 ? <ListOfSelectedIndicators classes={classes} searchIndicator={searchIndicator}
                                                    indicatorType={indicatorType} selectedIndicators={selectedIndicators}
                                                    indicatorDetails={indicatorsData}/>
          : tabValue === 1 ? <ListOfIndicators classes={classes}
                                               indicatorDetails={selectedIndicators}/> : <></>}
      </Grid>

      <Grid container justify="space-between" lg={9}>
        <Grid item>
          <Button onClick={handleStepBackward} className={styles.buttonSpacing}> Back </Button>

          <ModalCreateNewIndicator openDialog={openCreateNewIndicator}
                                   setOpenDialog={setOpenCreateNewIndicator}/>

          <Button variant="contained" color="primary" disabled={selectedIndicators.length === 0}
                  onClick={handleStepForward} className={styles.buttonSpacing}>
            Next
          </Button>

          <Tooltip arrow placement="bottom" title="Create a new custom indicator">
            <Button
              onClick={selectedPlatforms.length === 0 ?
                handleCreateIndicator : () => setIndicatorInProgress(true)}
              startIcon={<AddIcon/>} variant="outlined" color="inherit">
              New Indicator
            </Button>
          </Tooltip>
        </Grid>

        <Grid item>
          {selectedPlatforms.length !== 0 ? (
            <>
              <Tooltip arrow placement="bottom" title={<Typography>Discard the ongoing custom Indicator</Typography>}>
                <Button startIcon={<DeleteIcon/>} className={styles.buttonSpacing}
                        color="secondary" onClick={handleResetIndicatorSession}>
                  Discard Indicator
                </Button>
              </Tooltip>

              <Tooltip arrow placement="bottom" title={<Typography>Back to Indicator customization</Typography>}>
                <Button variant="outlined" startIcon={<EditIcon/>} className={styles.buttonSpacing}
                        color="primary" onClick={handleBackToIndicatorEditor}>
                  Draft Indicator
                </Button>
              </Tooltip>
            </>) : <></>}
        </Grid>

      </Grid>


      <ModalMessage
        dialogTitle={"You have an ongoing indicator draft!"}
        dialogPrimaryContext={
          <Grid container direction="column">
            <Typography  gutterBottom>Would you like to go to the ongoing indicator
              draft?</Typography>
          </Grid>}
        openDialog={indicatorInProgress}
        setOpenDialog={setIndicatorInProgress}
        primaryAction={handleCreateIndicator}
        primaryButton={"create custom indicator"}
        secondaryAction={handleBackToIndicatorEditor}
        secondaryButton={"to draft"}
      />
    </>
  )
}
